<?php

namespace App\Services\Admin\Goods;

use App\Exceptions\ShopException;
use App\Models\Applet\Shop\ShopGoodsModel;
use App\Services\BaseService;
use Exception;

class GoodsService extends BaseService
{

    /**
     * 商品列表
     * @param array $params
     * @return array[]
     * @throws Exception
     */
    public function list(array $params): array
    {
        $total = $this->getShopGoodsModel()->adminTotal($params);

        // 查询商品列表
        $goodsList = $this->getShopGoodsModel()->adminList($params, [
            'id', 'category_id', 'name', 'cover_img', 'price', 'quantity', 'sales_quantity',
            'show_sales_quantity', 'weight', 'shipping_fee', 'status', 'listing_time'
        ]);

        // 查询分类
        $categoryIds = array_column($goodsList, 'category_id');

        $categoryList = $this->getShopCategoryModel()->getItemsByIds($categoryIds, [
            'id', 'title'
        ]);
        $categoryListMap = array_column($categoryList, null, 'id');

        $list = [];
        foreach ($goodsList as $item) {
            $list[] = [
                'id' => $item['id'],
                'categoryInfo' => $categoryListMap[$item['category_id']] ?? [],
                'name' => $item['name'],
                'coverImg' => $item['cover_img'],
                'price' => $item['price'] / 100,
                'quantity' => $item['quantity'],
                'salesQuantity' => $item['sales_quantity'],
                'showSalesQuantity' => $item['show_sales_quantity'],
                'weight' => $item['weight'] / 1000,
                'shippingFee' => $item['shipping_fee'] / 100,
                'status' => $item['status'],
                'listingTime' => $item['listing_time'] ?? ''
            ];
        }

        return [
            'list' => $list,
            'total' => $total
        ];
    }

    /**
     * 商品详情
     * @param array $params
     * @return array
     * @throws ShopException
     * @throws Exception
     */
    public function detail(array $params): array
    {
        // 查询商品
        $goodsInfo = $this->getShopGoodsModel()->getItemById($params['id'], [
            'id', 'category_id', 'province_id', 'city_id', 'region_id', 'name', 'cover_img', 'price', 'quantity', 'sales_quantity',
            'show_sales_quantity', 'weight', 'shipping_fee', 'status', 'listing_time', 'params'
        ]);
        if (empty($goodsInfo)) {
            throw new ShopException('商品不存在', ShopException::CODE_1001);
        }

        $categoryInfo = $this->getShopCategoryModel()->getItemById($goodsInfo['category_id'], [
            'id', 'title'
        ]);

        return [
            'id' => $goodsInfo['id'],
            'categoryInfo' => $categoryInfo,
            'name' => $goodsInfo['name'],
            'coverImg' => $goodsInfo['cover_img'],
            'price' => $goodsInfo['price'] / 100,
            'quantity' => $goodsInfo['quantity'],
            'salesQuantity' => $goodsInfo['sales_quantity'],
            'showSalesQuantity' => $goodsInfo['show_sales_quantity'],
            'weight' => $goodsInfo['weight'] / 1000,
            'shippingFee' => $goodsInfo['shipping_fee'] / 100,
            'status' => $goodsInfo['status'],
            'listingTime' => $goodsInfo['listing_time'],
            'params' => json_decode($goodsInfo['params'], true) ?? [],
        ];
    }

    /**
     * 创建商品
     * @return void
     * @throws Exception
     */
    public function create(array $params)
    {
        // 查询分类是否存在
        $categoryInfo = $this->getShopCategoryModel()->getItemById($params['categoryId']);
        if (empty($categoryInfo)) {
            throw new ShopException('分类不存在', ShopException::CODE_2001);
        }

        $createShopGoods = [
            'category_id' => $params['categoryId'],
            'name' => $params['name'],
            'cover_img' => $params['coverImg'],
            'price' => $params['price'] * 100,
            'quantity' => $params['quantity'],
            'show_sales_quantity' => $params['showSalesQuantity'],
            'weight' => $params['weight'] * 1000,
            'shipping_fee' => $params['shippingFee'] * 100,
            'status' => $params['status'],
            'params' => json_encode($params['params'], true) ?? "",
        ];

        $this->getShopGoodsModel()->addItem($createShopGoods);
    }

    /**
     * 更新商品
     * @return void
     * @throws Exception
     */
    public function update(array $params)
    {
        $updateShopGoods = [];
        if (!empty($params['categoryId'])) {
            // 查询分类是否存在
            $categoryInfo = $this->getShopCategoryModel()->getItemById($params['categoryId']);
            if (empty($categoryInfo)) {
                throw new ShopException('分类不存在', ShopException::CODE_2001);
            }
            $updateShopGoods['category_id'] = $params['categoryId'];
        }
        if (!empty($params['name'])) {
            $updateShopGoods['name'] = $params['name'];
        }
        if (!empty($params['coverImg'])) {
            $updateShopGoods['cover_img'] = $params['coverImg'];
        }
        if (isset($params['price'])) {
            $updateShopGoods['price'] = $params['price'] * 100;
        }
        if (isset($params['quantity'])) {
            $updateShopGoods['quantity'] = $params['quantity'];
        }
        if (isset($params['showSalesQuantity'])) {
            $updateShopGoods['show_sales_quantity'] = $params['showSalesQuantity'];
        }
        if (isset($params['weight'])) {
            $updateShopGoods['weight'] = $params['weight'] * 1000;
        }
        if (isset($params['shippingFee'])) {
            $updateShopGoods['shipping_fee'] = $params['shippingFee'] * 100;
        }
        if (isset($params['status'])) {
            $updateShopGoods['status'] = $params['status'];
        }
        if (!empty($params['params'])) {
            $updateShopGoods['params'] = json_encode($params['params'], true);
        }
        
        $this->getShopGoodsModel()->updateItemById($params['id'], $updateShopGoods);
    }

    /**
     * 删除商品
     * @return void
     * @throws Exception
     */
    public function delete(array $params)
    {
        $shopGoods = $this->getShopGoodsModel()->getItemById($params['id'], [
            'id', 'status'
        ]);
        if (empty($shopGoods)) {
            throw new ShopException('商品不存在', ShopException::CODE_1001);
        }
        if ($shopGoods['status'] == ShopGoodsModel::STATUS_YES) {
            throw new ShopException('已上架的商品不能删除', ShopException::CODE_1005);
        }

        $this->getShopGoodsModel()->deleteItemById($params['id']);
    }

    /**
     * 上架/下架
     * @return void
     * @throws ShopException
     * @throws Exception
     */
    public function release(array $params)
    {
        $shopGoods = $this->getShopGoodsModel()->getItemById($params['id']);
        if (empty($shopGoods)) {
            throw new ShopException('商品不存在', ShopException::CODE_1001);
        }

        $updateData = [];
        if ($params['status'] == ShopGoodsModel::STATUS_YES) {
            $updateData['status'] = ShopGoodsModel::STATUS_YES;
            $updateData['listing_time'] = date('Y-m-d H:i:s');
        } else {
            $updateData['status'] = ShopGoodsModel::STATUS_NO;
            $updateData['listing_time'] = null;
        }

        $this->getShopGoodsModel()->updateItemById($params['id'], $updateData);
    }

    /**
     * 推荐/取消推荐
     * @return void
     * @throws ShopException
     * @throws Exception
     */
    public function recommend(array $params)
    {
        // 查询认养商品
        $shopGoods = $this->getShopGoodsModel()->getItemById($params['id']);
        if (empty($shopGoods)) {
            throw new ShopException('商品不存在', ShopException::CODE_1001);
        }

        $updateData = [
            'is_recommend' => $params['status'],
        ];

        // 更新上下架
        $this->getShopGoodsModel()->updateItemById($params['id'], $updateData);
    }
}
